from sqlalchemy import PrimaryKeyConstraint, Sequence
from sqlalchemy.dialects.postgresql import TIMESTAMP

from tzq.extensions import db


class Log(db.Model):
    """ 日志表。记录修改或删除的数据情况 """
    __tablename__ = 'dm_log_t'
    __table_args__ = (
        PrimaryKeyConstraint('log_id', name='dm_log_pk', comment='主键约束'),
        {'comment': '日志表。记录修改或删除的数据情况'},
    )
    log_id = db.Column(
        db.BigInteger,
        Sequence('dm_log_s'),
        primary_key=True,
        server_default=Sequence('dm_log_s').next_value(),
        nullable=False,
        comment='主键ID'
    )
    business_type = db.Column(db.String(100), nullable=False, comment='业务类型：国际化、菜单')
    log_type = db.Column(db.String(100), nullable=False, comment='日志类型：修改、删除')
    ip = db.Column(db.String(50), nullable=False, comment='操作的IP地址')
    field_name = db.Column(db.String(3000), comment='修改或删除的字段名字')
    old_value = db.Column(db.Text, nullable=False, comment='修改或删除的旧值')
    new_value = db.Column(db.Text, comment='修改或删除的新值')
    creation_date = db.Column(TIMESTAMP(timezone=False, precision=0), nullable=False,
                              server_default=db.func.clock_timestamp(), comment='创建时间')

    def to_dict(self):
        return {
            'log_id': self.log_id,
            'business_type': self.business_type,
            'log_type': self.log_type,
            'ip': self.ip,
            'field_name': self.field_name,
            'old_value': self.old_value,
            'new_value': self.new_value,
            'creation_date': self.creation_date.strftime('%Y-%m-%d %H:%M:%S'),
        }


class Version(db.Model):
    """ 版本表。记录版本情况 """
    __tablename__ = 'dm_version_t'
    __table_args__ = (
        PrimaryKeyConstraint('version_id', name='dm_version_pk', comment='主键约束'),
        {'comment': '版本表。记录版本情况'},
    )
    version_id = db.Column(
        db.BigInteger,
        Sequence('dm_version_s'),
        primary_key=True,
        server_default=Sequence('dm_version_s').next_value(),
        nullable=False,
        comment='主键ID'
    )
    online_date = db.Column(TIMESTAMP(timezone=False, precision=0), nullable=False,
                            server_default=db.func.current_date(), comment='上线时间')
    creation_date = db.Column(TIMESTAMP(timezone=False, precision=0), nullable=False,
                              server_default=db.func.clock_timestamp(), comment='创建时间')

    def to_dict(self):
        return {
            'version_id': self.version_id,
            'online_date': self.online_date,
            'creation_date': self.creation_date.strftime('%Y-%m-%d %H:%M:%S'),
        }
